import { createRouter, createWebHistory } from 'vue-router';
import login from '@/View/User/Login.vue';
import Home from '@/View/Home.vue';
import register from '@/View/User/Register.vue';
import personal from '@/View/personal/index.vue';


import resume from '@/View/resume/index.vue';
import searchJob from '@/View/MyJobs/searchJob.vue';
import jobinfovue from "@/views/Work/jobinfo.vue";
import company from '@/View/MyJobs/company.vue';
import personalSelected from '@/View/MyJobs/personalSelected.vue';


import store from '@/store/index';
import storageUtils from '@/util';
import agreement from '@/View/User/Agreement.vue';
import forgetPassword from '@/View/User/ForgetPassword.vue';
//定义路由规则
const routes = [
    {
        path: '/',
        redirect: '/Home' // 根目录重定向到 /Home
    },
    //登录页面
    {
        name: 'login',
        path: "/login",
        component: login
    },
    //主页面
    {
        name: 'Home',
        path: "/Home",
        component: Home
    },
    //注册页面
    {
        name: 'register',
        path: '/register',
        component: register
    },
    {
        name: 'personal',
        path: "/personal",
        component: personal
    },

    {
        name: 'resume',
        path: "/resume",
        component: resume
    },

    {
        path: '/searchJob',
        name: 'searchJob',
        component: searchJob,
        meta: {
            title: '职位搜索-高级搜索', // 可选：用于设置页面标题
        },
    },

    {
        path: '/jobinfo/:id',
        component: jobinfovue
    },

  {
        path: '/company/:enterpriseId',
        name: 'company',
        component: company
      },{
        path:'/personalSelected',
        name:'personalSelected',
        component: personalSelected
      },

,
    // 用户协议页面

    {
        name: 'agreement',
        path: '/agreement',
        component: agreement
    },

    //忘记密码页面
    {
        name: 'forgetPassword',
        path: '/forgetPassword',
        component: forgetPassword
    },


];

//创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes,
})



 //白名单路由,不拦截以下的路由，可自行添加或注释掉
const whiteList = ['Home', 'login', 'register', 'agreement', 'forgetPassword', ];


//路由守卫
router.beforeEach((to, from) => {


    //初始跳转到主页面
    //如果是白名单就不拦截
    //如果跳转到主页面并且sessionStorage有数据就存入vuex，防止登录失效
    if (whiteList.includes(to.name)) {
        if (to.name == 'Home' && storageUtils.getSessionObject('loginUser')) {
            store.dispatch('RESTORE_VUEX');
        }
        return true;
    }
    //如果vuex中没有token就检查session中的，都没有就返回登陆

    if (!store.state.token) {
        if (!storageUtils.getSessionObject('loginUser')) {
            router.push({ name: 'login' });
        } else {
            store.dispatch('RESTORE_VUEX');
        }
    }
    return true;

})
 



export default router;